package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Query;
import com.mp.approvalreq.entity.Request;
import com.mp.approvalreq.service.RequestServicePrx;
import com.mp.approvalreq.util.ApprovalUtils;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import com.qq.tars.client.util.ServantUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 获得我申请的审批
 */
@WebServlet("/getMyRequestList")
public class GetMyRequestList extends AbstractServlet {
	private static final long serialVersionUID = -6524473373623928868L;

	private static final Logger logger = LoggerFactory.getLogger(GetMyRequestList.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	/**
	 * {"dataNum":20,"finishedSequence":"-1,0","page":1}       : 我申请的待处理
	 * {"page":1,"dataNum":20,"finishedSequence":"-2,1,2,3"}   : 我申请的已处理
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			User user = getReqUser(req);

			Request request = getRequest(req);
			check(request);

			RequestServicePrx requestServicePrx = ServantUtils.getObject(RequestServicePrx.class);
			Query query = getQuery(req, user, request);
			List<Request> list = requestServicePrx.getUserRequestList(query);

			ApprovalUtils.replaceNewExpenseValue(list);

			returnResult(resp, list);
		} catch (Throwable e) {
			onThrowable(req, resp, e);
		}
	}

	private void returnResult(HttpServletResponse resp, List<Request> requests) throws IOException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", "0");
		jsonObject.put("res_info", "获得成功");
		jsonObject.put("item", requests);

		logger.info(jsonObject.toJSONString());

		printJson(resp, jsonObject.toJSONString());
	}

	private Request getRequest(HttpServletRequest req) throws IOException {
		String reqBody = getContent(req);
		logger.info(String.format("获得我申请的审批：json参数值：%s", reqBody));

		Request request;
		try {
			request = JSONObject.parseObject(reqBody, Request.class);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RpcServerLogicalException(1, "审批内容提交失败，请稍候再试");
		}

		return request;
	}

	protected void check(Request request) {
		if (StringUtils.isEmpty(request.getFinishedSequence())) {
			throw new RpcServerLogicalException(1, "请求ID不正确");
		}
	}
}
